import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import './PhotoDetail.css';

interface PhotoMetadata {
  id: string;
  filename: string;
  path: string;
  size: number;
  width: number;
  height: number;
  format: string;
  createdAt: string;
  modifiedAt: string;
  exif?: {
    camera?: string;
    lens?: string;
    focalLength?: string;
    aperture?: string;
    shutterSpeed?: string;
    iso?: string;
    flash?: string;
    gps?: {
      latitude: number;
      longitude: number;
    };
  };
}

/**
 * 照片详情页面组件
 * 显示照片的详细信息和元数据
 */
export default function PhotoDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [photo, setPhoto] = useState<PhotoMetadata | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showMetadata, setShowMetadata] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    if (id) {
      loadPhotoDetail(id);
    }
  }, [id]);

  /**
   * 加载照片详情
   */
  const loadPhotoDetail = async (photoId: string) => {
    try {
      setLoading(true);
      setError(null);
      
      // TODO: 实现获取照片详情的 API
      // const photoData = await window.photosAPI.getPhotoById(photoId);
      // setPhoto(photoData);
      
      // 临时模拟数据
      const mockPhoto: PhotoMetadata = {
        id: photoId,
        filename: 'IMG_001.jpg',
        path: '/Users/user/Pictures/IMG_001.jpg',
        size: 2048576,
        width: 1920,
        height: 1080,
        format: 'JPEG',
        createdAt: '2024-01-15T10:30:00Z',
        modifiedAt: '2024-01-15T10:30:00Z',
        exif: {
          camera: 'Canon EOS R5',
          lens: 'RF 24-70mm f/2.8L IS USM',
          focalLength: '50mm',
          aperture: 'f/2.8',
          shutterSpeed: '1/125s',
          iso: 'ISO 400',
          flash: 'No Flash'
        }
      };
      setPhoto(mockPhoto);
      
    } catch (err) {
      console.error('Failed to load photo detail:', err);
      setError(err instanceof Error ? err.message : '加载照片详情失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 返回图库
   */
  const handleBackToLibrary = () => {
    navigate('/');
  };

  /**
   * 切换元数据显示
   */
  const toggleMetadata = () => {
    setShowMetadata(!showMetadata);
  };

  /**
   * 切换全屏模式
   */
  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  /**
   * 删除照片
   */
  const handleDeletePhoto = async () => {
    if (!photo) return;

    try {
      const result = await (window as any).photosAPI?.showMessageBox({
        type: 'warning',
        title: '确认删除',
        message: '确定要删除这张照片吗？',
        detail: '此操作不可撤销',
        buttons: ['取消', '删除'],
        defaultId: 0,
        cancelId: 0
      });

      if (result.response === 1) {
        // TODO: 实现删除照片的 API
        // await window.photosAPI.deletePhoto(photo.id);
        navigate('/');
      }
    } catch (err) {
      console.error('Failed to delete photo:', err);
      await (window as any).photosAPI?.showMessageBox({
        type: 'error',
        title: '删除失败',
        message: '删除照片时发生错误',
        detail: err instanceof Error ? err.message : '未知错误'
      });
    }
  };

  /**
   * 在文件管理器中显示
   */
  const handleShowInFinder = async () => {
    if (!photo) return;

    try {
      // TODO: 实现在文件管理器中显示的 API
      // await window.photosAPI.showItemInFolder(photo.path);
    } catch (err) {
      console.error('Failed to show in finder:', err);
    }
  };

  /**
   * 格式化文件大小
   */
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  /**
   * 格式化日期
   */
  const formatDate = (date: string): string => {
    return new Date(date).toLocaleString('zh-CN');
  };

  if (loading) {
    return (
      <div className="photo-detail loading">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    );
  }

  if (error || !photo) {
    return (
      <div className="photo-detail error">
        <div className="error-content">
          <h2>加载失败</h2>
          <p>{error || '照片不存在'}</p>
          <button className="btn primary" onClick={handleBackToLibrary}>
            返回图库
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={`photo-detail ${isFullscreen ? 'fullscreen' : ''}`}>
      {/* 工具栏 */}
      {!isFullscreen && (
        <div className="toolbar">
          <div className="toolbar-left">
            <button className="btn secondary" onClick={handleBackToLibrary}>
              ← 返回图库
            </button>
            <h1 className="photo-title">{photo.filename}</h1>
          </div>
          <div className="toolbar-right">
            <button 
              className="btn secondary"
              onClick={toggleMetadata}
              title="显示/隐藏元数据"
            >
              📊 元数据
            </button>
            <button 
              className="btn secondary"
              onClick={handleShowInFinder}
              title="在文件管理器中显示"
            >
              📁 显示文件
            </button>
            <button 
              className="btn secondary"
              onClick={toggleFullscreen}
              title="全屏查看"
            >
              🔍 全屏
            </button>
            <button 
              className="btn danger"
              onClick={handleDeletePhoto}
              title="删除照片"
            >
              🗑️ 删除
            </button>
          </div>
        </div>
      )}

      <div className="photo-content">
        {/* 照片显示区域 */}
        <div className="photo-viewer">
          <div className="photo-container">
            <img 
              src={`file://${photo.path}`}
              alt={photo.filename}
              className="photo-image"
              onClick={toggleFullscreen}
            />
            
            {isFullscreen && (
              <div className="fullscreen-controls">
                <button 
                  className="btn secondary"
                  onClick={toggleFullscreen}
                  title="退出全屏"
                >
                  ✕ 退出全屏
                </button>
              </div>
            )}
          </div>
        </div>

        {/* 元数据面板 */}
        {showMetadata && !isFullscreen && (
          <div className="metadata-panel">
            <div className="metadata-header">
              <h3>照片信息</h3>
              <button 
                className="btn secondary small"
                onClick={toggleMetadata}
              >
                ✕
              </button>
            </div>

            <div className="metadata-content">
              {/* 基本信息 */}
              <div className="metadata-section">
                <h4>基本信息</h4>
                <div className="metadata-items">
                  <div className="metadata-item">
                    <span className="label">文件名:</span>
                    <span className="value">{photo.filename}</span>
                  </div>
                  <div className="metadata-item">
                    <span className="label">格式:</span>
                    <span className="value">{photo.format}</span>
                  </div>
                  <div className="metadata-item">
                    <span className="label">尺寸:</span>
                    <span className="value">{photo.width} × {photo.height}</span>
                  </div>
                  <div className="metadata-item">
                    <span className="label">文件大小:</span>
                    <span className="value">{formatFileSize(photo.size)}</span>
                  </div>
                  <div className="metadata-item">
                    <span className="label">创建时间:</span>
                    <span className="value">{formatDate(photo.createdAt)}</span>
                  </div>
                  <div className="metadata-item">
                    <span className="label">修改时间:</span>
                    <span className="value">{formatDate(photo.modifiedAt)}</span>
                  </div>
                </div>
              </div>

              {/* EXIF 信息 */}
              {photo.exif && (
                <div className="metadata-section">
                  <h4>拍摄信息</h4>
                  <div className="metadata-items">
                    {photo.exif.camera && (
                      <div className="metadata-item">
                        <span className="label">相机:</span>
                        <span className="value">{photo.exif.camera}</span>
                      </div>
                    )}
                    {photo.exif.lens && (
                      <div className="metadata-item">
                        <span className="label">镜头:</span>
                        <span className="value">{photo.exif.lens}</span>
                      </div>
                    )}
                    {photo.exif.focalLength && (
                      <div className="metadata-item">
                        <span className="label">焦距:</span>
                        <span className="value">{photo.exif.focalLength}</span>
                      </div>
                    )}
                    {photo.exif.aperture && (
                      <div className="metadata-item">
                        <span className="label">光圈:</span>
                        <span className="value">{photo.exif.aperture}</span>
                      </div>
                    )}
                    {photo.exif.shutterSpeed && (
                      <div className="metadata-item">
                        <span className="label">快门速度:</span>
                        <span className="value">{photo.exif.shutterSpeed}</span>
                      </div>
                    )}
                    {photo.exif.iso && (
                      <div className="metadata-item">
                        <span className="label">ISO:</span>
                        <span className="value">{photo.exif.iso}</span>
                      </div>
                    )}
                    {photo.exif.flash && (
                      <div className="metadata-item">
                        <span className="label">闪光灯:</span>
                        <span className="value">{photo.exif.flash}</span>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* GPS 信息 */}
              {photo.exif?.gps && (
                <div className="metadata-section">
                  <h4>位置信息</h4>
                  <div className="metadata-items">
                    <div className="metadata-item">
                      <span className="label">纬度:</span>
                      <span className="value">{photo.exif.gps.latitude.toFixed(6)}</span>
                    </div>
                    <div className="metadata-item">
                      <span className="label">经度:</span>
                      <span className="value">{photo.exif.gps.longitude.toFixed(6)}</span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}